import React from 'react'
import {
    error, TreeList, info, success, IconFont, Input, Select, Modal, Checkbox, Tree, Link, TitleBar, Radio,
    error as err
} from '../../ui-components'
import { connect } from 'react-redux'
import style from './style.team-manage'
import util from '../../util'
import { u } from '../../actions/util';
import cx from 'classnames'

const ROOT_TEAM = '2b1e6d025ac28868'

export
const makeTeamTree = (teams) => {
    //const { teams } = this.props.team
    if (util.isNull(teams)) return []

    function find(list) {
        if (!list.length) return []
        return list.map(item => {
            return {
                ...item,
                teams: find.call(this, teams.filter(team => util.isEqual(team.parentTeamId, item.teamId)))
            }
        })
    }

    return find.call(this, [{ teamId: ROOT_TEAM, teamName: 'root team' }])
}

function ToolTip(props){
    return(
        <a href="javascript:void(0);" className={style["toolTip"]}>
            <span className={style["toolTip-content"]}>{props.title}</span>
            {
                props.children
            }
        </a>
    );
}

export default
@connect(({team, app}) => ({team, app}))
class TeamManage extends React.Component {

    moveTeamInit = {
        moveTeam: false,
        teamIds: [],
        userIds: [],
        editAll: false
    }

    createTeamInit = {
        createTeam: false,
        createdTeamName: '',
        teamTree: false,
        selectedTeam: null,
        nextTeamId:0,
    }

    deleteTeamInit = {
        deleteTeam: false,
        deletedTeam: {}
    }

    updateTeamInit = {
        updateTeam: false,
        updatedTeam: {},
        updateNextTeamId: 0
    }

    state = {
        rootTeamMemeber: {},
        ...this.createTeamInit,
        ...this.deleteTeamInit,
        ...this.moveTeamInit,
        ...this.updateTeamInit,
    }

    handleCheckUser(e, user, parentTeamId=ROOT_TEAM) {
        e.stopPropagation()
        const { userIds } = this.state
        if (userIds.some(u => u.idValue == user.userId)) {
            this.setState({
                userIds: this.state.userIds.filter(u => u.idValue != user.userId)
            })
        } else {
            this.setState({
                userIds: [
                    ...this.state.userIds,
                    {
                        idValue: user.userId,
                        parentTeamId
                    }
                ],
                teamIds: this.state.teamIds.filter(t => t.idValue != parentTeamId)
            })
        }
    }

    handleCheckTeam(e, team, parentTeamId=ROOT_TEAM) {
        e.stopPropagation()
        const { teamIds } = this.state
        if (teamIds.some(t => t.idValue == team.teamId)) {
            this.setState({
                teamIds: this.state.teamIds.filter(t => t.idValue != team.teamId)
            })
        } else {
            this.setState({
                teamIds: [
                    ...this.state.teamIds
                        .filter(obj => obj.idValue != parentTeamId)
                        .filter(obj => {
                            if (obj.parentTeamId == team.teamId) return false
                            return true
                        }),
                    {
                        idValue: team.teamId,
                        parentTeamId
                    }
                ],
                // 取消子节点
                userIds: this.state.userIds.filter(obj => {
                    if (obj.parentTeamId == team.teamId) return false
                    return true
                })
            })
        }
    }

    moveTeam() {
        const { teamId } = this.state.selectedTeam || {}
        if (!teamId) return error('请选择部门!')
        const { teamIds, userIds } = this.state
        info('移动中...')
        this.props.moveTeam({
            teamIds: teamIds.map(t => ({ idValue: t.idValue })),
            userIds: userIds.map(u => ({ idValue: u.idValue })),
            toTeamId: teamId
        }, () => {
            success('移动成功!')
            this.setState({
                rootTeamMemeber: {}
            })
            this.fetchTeamMemeber(ROOT_TEAM)
            this.props.actions.fetchProfile(u.userId);
        })
        this.cancelMoveTeam()
    }

    cancelMoveTeam() {
        this.setState({
            ...this.state,
            ...this.moveTeamInit
        })
    }

    cancelDeleteTeam() {
        this.setState({
            ...this.state,
            ...this.deleteTeamInit
        })
    }

    cancelUpdateTeam() {
        this.setState({
            ...this.updateTeamInit
        })
    }

    deleteTeam() {
        info('删除部门中...')
        this.props.deleteTeam(this.state.deletedTeam.teamId, (teamId,res) => {
            const { rootTeamMemeber } = this.state;
            if(res.code == 4030201){
                this.props.deleteTeamHasChildren(teamId,(teamId,res)=> {
                    this.setState({
                        rootTeamMemeber: {
                            ...rootTeamMemeber,
                            teamVOs: rootTeamMemeber.teamVOs.map(team => this.tranverseDeleteTeam(team, teamId))
                        }
                    })
                })
                this.cancelDeleteTeam()
                return;
            }

            const code = '' + res.code
            if (/^202\d+$/.exec(code)) {
                error(res.msg)
                return;
            }

            if (!/^20\d+$/.exec(code)) {
                error(res.msg)
                return;
            }


            success('删除部门成功!')
            this.setState({
                rootTeamMemeber: {
                    ...rootTeamMemeber,
                    teamVOs: rootTeamMemeber.teamVOs.map(team => this.tranverseDeleteTeam(team, teamId))
                }
            })
        })
        this.cancelDeleteTeam()
    }

    updateTeam() {
        info('更新部门中');
        this.props.updateTeam(this.state.updatedTeam.teamId,this.state.updatedTeam,teamId => {
            success('更新部门成功');
            this.setState({
                rootTeamMemeber: {}
            });
            this.fetchTeamMemeber(ROOT_TEAM);
            this.cancelUpdateTeam();
        });
    }

    requestMoveUser(e, user) {
        e.stopPropagation()
        this.props.fetchTeams()
        this.setState({
            userIds: [{idValue: user.userId}],
            moveTeam: true
        })
    }

    requestMoveTeam(e, team) {
        e.stopPropagation()
        this.props.fetchTeams()
        this.setState({
            teamIds: [{idValue: team.teamId}],
            moveTeam: true
        })
    }

    requestDeleteTeam(e, team) {
        e.stopPropagation()
        this.setState({
            deletedTeam: team,
            deleteTeam: true
        })
    }

    requestUpdateTeam(e, team) {
        this.props.fetchTeams()
        e.stopPropagation();
        this.setState({
            updatedTeam: {...team},
            updateTeam: true,
        })
    }

    requestCreateTeam() {
        this.props.fetchTeams()
        util.dialog.call(this, 'createTeam')
    }

    createTeam() {
        const { selectedTeam, createdTeamName, nextTeamId } = this.state
        if (!selectedTeam || util.isNull(createdTeamName)) return error('请填写名称和选择部门!')
        info('创建部门中..')
        this.props.createTeam({
            teamName: createdTeamName,
            parentTeamId: selectedTeam.teamId,
            /*teamMemberNumber:nextTeamId*/
        }, newTeam => {
            success('创建部门成功!')
            const { rootTeamMemeber } = this.state
            this.setState({
                rootTeamMemeber: {
                    ...rootTeamMemeber,
                    teamVOs: rootTeamMemeber.teamVOs.map(team => this.tranverseCreateTeam(team, newTeam))
                }
            })
        })
        this.cancelCreateTeam()
    }

    cancelCreateTeam() {
        this.setState({
            ...this.state,
            ...this.createTeamInit
        })
    }

    parentTeamId = null

    toggleTeamMemeber(team) {
        if (!team.teamMemeber) this.fetchTeamMemeber(team.teamId)
        else this.clearTeamMemeber(team.teamId)
    }

    renderTeams(list, parentTeamId) {
        if (util.isNull(list)) return null
        const orgTeamId = (this.props.app.org.teamVO || {}).teamId;
        return (
            <ul className={style.teams}>
                {
                    list.map((v, i) => (
                        <li key={i}>
              <span
                  className={cx(style['team-content'], { [style['has-children']]: v.teamMemeber })}
                  onClick={() => this.toggleTeamMemeber(v)}
              >
                <span>
                  <Checkbox active={this.state.teamIds.some(t => t.idValue == v.teamId)} className={style.check} onClick={e => this.handleCheckTeam(e, v, parentTeamId)}/>
                    {
                        v.hasSubordinate &&
                        <IconFont
                            className={style.arrow}
                            size="12"
                            value="arrow"
                        />
                    }
                    <IconFont value="team" className={style['team-icon']}/>
                  <span className={style['team-title-line']}>
                    <span>{ v.teamName }</span>
                    <span>{ `${v.teamMemberNumber || '0'}人`}</span>
                  </span>
                </span>
                  {
                      (orgTeamId && !util.isEqual(orgTeamId, v.teamId)) ? (
                          <span className={style['team-actions']}>
                      <Link label="编辑" onClick={e => this.requestUpdateTeam(e, v)}/>
                      <Link label="移动" onClick={e => this.requestMoveTeam(e, v)}/>
                      <Link label="删除" color="red" onClick={e => this.requestDeleteTeam(e, v)}/>
                    </span>
                      ) : null
                  }
              </span>
                            {
                                v.teamMemeber?
                                    <div className={style['sub-team-memeber']}>
                                        { this.renderTeams(v.teamMemeber.teamVOs, v.teamId) }
                                        { this.renderUsers(v.teamMemeber.coreUserProfileVOs, v.teamId) }
                                    </div>: null
                            }
                        </li>
                    ))
                }
            </ul>
        )
    }

    renderUsers(list, parentTeamId) {
        if (util.isNull(list)) return null
        return (
            <ul>
                {
                    list.map((v, i) => (
                        <li key={i}>
              <span className={style['user-content']}>
                <span className={style['user-profile']}>
                  <span>
                    <Checkbox active={this.state.userIds.some(u => u.idValue == v.userId)} className={style.check} onClick={e => this.handleCheckUser(e, v, parentTeamId)}/>
                    <Link
                        className={style['user-avatar']}
                        src={v.avatarUrl}
                        srcIcon="avatar"
                        width="26"
                        noHover
                    />
                      {/* 用户名称 */}
                      <span> <ToolTip title={v.emailAddress}>{ v.fullName }</ToolTip> {v.teamAdmin? <span className={style['team-admin']}>项目组负责人</span>: null} {v.jobTitleName? <span className={style['job-title']}>{v.jobTitleName}</span>: null}</span>
                  </span>
                  <span className={style['user-profile-actions']}>
                    <Link className={style['user-home']} icon="edit_profile" to={`#/hr/team-memeber-edit/${v.userId}`} target="_blank"/>
                  </span>
                </span>
                <span className={style['user-actions']}>
                  <Link label="移动" onClick={e => this.requestMoveUser(e, v)}/>
                </span>
              </span>
                        </li>
                    ))
                }
            </ul>
        )
    }

    renderTeamMemeber() {
        const { rootTeamMemeber } = this.state
        if (util.isNull(rootTeamMemeber)) return null
        const { coreUserProfileVOs, teamVOs } = rootTeamMemeber

        return (
            <div className={cx({[style['edit-all']]: this.state.editAll })}>
                { this.renderTeams(teamVOs) }
                { this.renderUsers(coreUserProfileVOs) }
            </div>
        )
    }

    fetchTeamMemeber(teamId) {
        this.parentTeamId = teamId
        this.props.fetchTeamMemeber(teamId)
    }

    tranverseTeam(team, cb) {
        const ret = cb(team)
        if (ret) {
            return {
                ...team,
                ...ret
            }
        } else if (team.teamMemeber) {
            return {
                ...team,
                teamMemeber: {
                    ...team.teamMemeber,
                    teamVOs: team.teamMemeber.teamVOs.map(team => this.tranverseTeam(team, cb))
                }
            }
        }
        return team
    }

    tranverseDeleteTeam(team, teamId) {
        if (!team.teamMemeber) return team
        return this.tranverseTeam(team, team => {
            if (!team.teamMemeber) return false
            if (!team.teamMemeber.teamVOs) return false
            if(team.teamId == teamId) {
                this.fetchTeams()
                return false
            }
            return team.teamMemeber.teamVOs.some(t => t.teamId == teamId) && {
                teamMemeber: {
                    ...team.teamMemeber,
                    teamVOs: team.teamMemeber.teamVOs.filter(_t => _t.teamId != teamId)
                }
            }
        })
    }

    tranverseCreateTeam(team, newTeam) {
        if (!team.teamMemeber) return team
        return this.tranverseTeam(team, team => {
            if (!team.teamMemeber) return false
            if (!team.teamMemeber.teamVOs) return false
            if (team.teamId == newTeam.parentTeamId) {
                return {
                    ...team,
                    teamMemeber: {
                        ...team.teamMemeber,
                        teamVOs: [
                            ...team.teamMemeber.teamVOs,
                            newTeam
                        ]
                    }
                }
            }
            return team.teamMemeber.teamVOs.some(t => util.isEqual(t.teamId, newTeam.parentTeamId)) && {
                teamMemeber: {
                    ...team.teamMemeber,
                    teamVOs: team.teamMemeber.teamVOs.map(_t => {
                        if (util.isEqual(_t.teamId, newTeam.parentTeamId) && _t.teamMemeber) {
                            return {
                                ..._t,
                                teamMemeber: {
                                    ..._t.teamMemeber,
                                    teamVOs: [
                                        ...(_t.teamMemeber.teamVOs || []),
                                        newTeam
                                    ]
                                }
                            }
                        }
                        return _t
                    })
                }
            }
        })
    }

    tranverseToggleUserStatus(team, user) {
        return this.tranverseTeam(team, team => {
            if (!team.teamMemeber) return false
            if (!team.teamMemeber.coreUserProfileVOs) return false
            return team.teamMemeber.coreUserProfileVOs.some(u => u.userId == user.userId) && {
                teamMemeber: {
                    ...team.teamMemeber,
                    coreUserProfileVOs: team.teamMemeber.coreUserProfileVOs.map(u => {
                        if (u.userId == user.userId) {
                            return {
                                ...u,
                                teamAdmin: !u.teamAdmin
                            }
                        }
                        return u
                    })
                }
            }
        })
    }

    tranverseLoad(team, curTeamMemeber) {
        return this.tranverseTeam(team, team => team.teamId == this.parentTeamId && { teamMemeber: curTeamMemeber })
    }

    tranverseClear(team, teamId) {
        return this.tranverseTeam(team, team => team.teamId == teamId && { teamMemeber: null })
    }

    clearTeamMemeber(teamId) {
        const { rootTeamMemeber } = this.state
        this.setState({
            rootTeamMemeber: {
                ...rootTeamMemeber,
                teamVOs: rootTeamMemeber.teamVOs.map(team => this.tranverseClear(team, teamId))
            }
        })
    }

    makeTree(curTeamMemeber) {
        const { rootTeamMemeber } = this.state
        if (util.isNull(rootTeamMemeber)) {
            this.setState({
                rootTeamMemeber: { ...curTeamMemeber }
            })
        } else {
            this.setState({
                rootTeamMemeber: {
                    ...rootTeamMemeber,
                    teamVOs: rootTeamMemeber.teamVOs.map(team => this.tranverseLoad(team, curTeamMemeber))
                }
            })
        }
    }

    componentDidMount() {
        this.fetchTeamMemeber(ROOT_TEAM)
    }

    componentWillReceiveProps(props) {
        if ((this.props.team.teamMemebers || []).length < (props.team.teamMemebers || []).length) {
            const curTeamMemeber = util.last(props.team.teamMemebers)
            this.makeTree(curTeamMemeber)

            // 根，
            // 默认再读取一级数据
            if (this.parentTeamId == ROOT_TEAM) {
                this.fetchTeamMemeber(curTeamMemeber.teamVOs[0].teamId)
            }
        }
    }

    handleSelectTeamTree(team) {
        this.setState({
            selectedTeam: team
        })
    }

    handleSelectSort(e){
        const sort = e.target.value;
        this.setState({
            nextTeamId:sort
        })
    }

    handleUpdateSelectSort(e){
        const team = this.state.updatedTeam;
        team.isTeamAdmin = e.target.value;
        this.setState({ updatedTeam :team})
    }

    renderTeamTree() {
        const { teams } = this.props.team
        const rootTeam = makeTeamTree(teams)[0]
        return (
            <TreeList
                onClick={::this.handleSelectTeamTree}
                root={rootTeam}
            />
        )
    }


    nextTeamTree() {
        const { teams } = this.props.team;
        const { selectedTeam } = this.state;
        let selectedTeamParent = new Array();
        teams && teams.map((value, i) => {
            if(selectedTeam != null && selectedTeam.teamId != null && selectedTeam.teamId === value.parentTeamId){
                selectedTeamParent.push(value);
            }
        })

        return (
            <Select
                onChange={::this.handleSelectSort}
            >
                <option value={selectedTeamParent.length + 1} >默认为最后</option>
                {
                    (selectedTeamParent || []).map((v, i) => (
                        <option key={i} value={i+1}>{"放"+ v.teamName +"之前"}</option>
                    ))
                }
                />
            </Select>
        )
    }

    updateNextTeamTree() {
        const { teams } = this.props.team
        const updatedTeam = this.state.updatedTeam;
        let selectedTeamParent = new Array();
        teams && teams.map((value, i) => {
            if(updatedTeam != null && updatedTeam.parentTeamId != null && updatedTeam.parentTeamId === value.parentTeamId && value.teamId != updatedTeam.teamId){
                selectedTeamParent.push(value);
            }
        })
        return (
            <Select
                onChange={::this.handleUpdateSelectSort}
                label={"所放顺序"}
            >
                <option value={selectedTeamParent.length + 1} >默认为最后</option>
                {
                    (selectedTeamParent || []).map((v, i) => (
                        <option key={i} value={i+1}>{"放"+ v.teamName +"之前"}</option>
                    ))
                }
                />
            </Select>
        )
    }

    toggleTeamTree() {
        this.setState({
            teamTree: !this.state.teamTree
        })
    }

    render() {
        const {label} = this.props;
        let actions = [
            {
                label: this.state.editAll? '移动全部': '批量操作',
                disabled: this.state.editAll && !this.state.userIds.length && !this.state.teamIds.length,
                onClick: () => {
                    if (!this.state.editAll) {
                        this.setState({ editAll: true })
                    } else {
                        this.props.fetchTeams()
                        this.setState({ moveTeam: true })
                    }
                },
                blueLine: !this.state.editAll
            },
            {
                label: '添加部门',
                handler: ::this.requestCreateTeam,
                disabled: this.state.editAll
            }
        ]
        if (this.state.editAll) {
            actions = [
                {
                    label: '取消批量操作',
                    onClick: () => this.setState({ editAll: false }),
                    blueLine: true
                },
                actions[0],
                actions[1]
            ]
        }
        return (
            <div>
                <TitleBar
                    label="组织架构管理"
                    actions={actions}
                    fixed
                />
                <div className={style['root-team-memeber']}>
                    { this.renderTeamMemeber() }
                </div>
                <Modal
                    className={style['team-create-dialog']}
                    active={this.state.createTeam}
                    onRequestClose={::this.cancelCreateTeam}
                    actions={[
                        'cancel',
                        ::this.createTeam
                    ]}
                    title="添加部门"
                >
                    <div className={style.createTeamForm}>
                        <div>
                            <div className={style.list}>
                                <Input
                                    value={this.state.createdTeamName}
                                    onChange={(e) => this.setState({ createdTeamName: e.target.value })}
                                    placeholder="部门名称"
                                />
                                {
                                    this.renderTeamTree()
                                }
                            {/*    {
                                    this.nextTeamTree()
                                }*/}
                            </div>
                        </div>
                    </div>
                </Modal>
                <Modal
                    className={style['team-create-dialog']}
                    active={this.state.updateTeam}
                    onRequestClose={::this.cancelUpdateTeam}
                    actions={[
                        'cancel',
                        ::this.updateTeam
                    ]}
                    title="编辑部门"
                >
                    <div className={style.createTeamForm}>
                        <div>
                            <div className={style.list}>
                                <Input
                                    value={this.state.updatedTeam.teamName || ''}
                                    onChange={(e) => {
                                        const team = this.state.updatedTeam;
                                        team.teamName = e.target.value;
                                        this.setState({ updatedTeam :team})
                                    }}
                                    label="部门名称"
                                />
                              {/*  {
                                    this.updateNextTeamTree()
                                }*/}
                            </div>
                        </div>
                    </div>
                </Modal>
                <Modal
                    active={this.state.deleteTeam}
                    onRequestClose={::this.cancelDeleteTeam}
                    actions={[
                        'cancel',
                        ::this.deleteTeam
                    ]}
                    title="删除部门"
                >
                    <div>
                        <p>确定删除`{`${this.state.deletedTeam.teamName || ''}`}`部门吗?</p>
                        {
                            (this.state.deletedTeam.hasSubordinate || this.state.deletedTeam.teamMemberNumber > 0)?
                            <div style={{color:"red"}}>(该团队下有其他部门或人员请谨慎操作)</div>:null
                        }
                    </div>
                </Modal>
                <Modal
                    active={this.state.moveTeam}
                    className={style['team-create-dialog']}
                    onRequestClose={::this.cancelMoveTeam}
                    actions={[
                        'cancel',
                        ::this.moveTeam
                    ]}
                    title="移动部门或成员"
                >
                    <div>
                        {
                            this.renderTeamTree()
                        }
                    </div>
                </Modal>
            </div>
        )
    }
}
